import { isNil } from 'lodash-es'
import { v4 as uuidv4 } from 'uuid'

export function getAssetsFile(url: string) {
  return new URL(`../assets/images/${url}`, import.meta.url).href
}

export const isDev = import.meta.env.MODE === 'development'

/**
 * 是否JSON
 */
export const isJSON = (str: any) => {
  if (typeof str === 'string') {
    try {
      const obj = JSON.parse(str)
      return typeof obj === 'object' && obj
    } catch (e) {
      return false
    }
  }
  return false
}

/**
 * 数组对象根据字段去重
 */
export function uniqueArrayObject(arr = [], key = 'id') {
  const obj = arr.reduce((acc, cur) => {
    acc[cur[key]] = cur
    return acc
  }, {})
  return Object.values(obj)
}

export const getListByDataMap = (dataMap: Record<string, any>, isNumberValue?: boolean) => {
  isNumberValue = isNil(isNumberValue) ? true : isNumberValue
  return Object.entries(dataMap).map(([value, label]) => ({
    label,
    value: isNumberValue ? +value : value
  }))
}

export const setFormData = (formData: any, data: any) => {
  if (!formData || !data) {
    return
  }
  Object.keys(formData).forEach((key) => {
    const val = data[key]
    if (val !== undefined) {
      formData[key] = val
    }
  })
}

/**
 * 获取UUID
 */
export const getUUID = () => {
  return uuidv4()
}

/**
 * 获取对象原型上的方法，排除构造方法
 */
export function getPrototypeMethods<T>(obj: T): {
  [key: string]: (...args: any[]) => any
} {
  const methods: { [key: string]: (...args: any[]) => any } = {}
  let proto = Object.getPrototypeOf(obj)
  while (proto && proto !== Object.prototype) {
    Object.getOwnPropertyNames(proto).forEach((name) => {
      if (name !== 'constructor' && typeof (obj as any)[name] === 'function') {
        methods[name] = (obj as any)[name]
      }
    })
    proto = Object.getPrototypeOf(proto)
  }
  return methods
}

export const getPxValue = (data: string | number) => {
  let value = 0
  try {
    if (typeof data === 'number') {
      value = data
    } else {
      value = +data?.replace('px', '') || 0
    }
  } catch (e) {
    value = 0
  }
  return value
}

export const setPxValue = (data: string | number) => {
  if (typeof data === 'number') {
    return `${data}px`
  }
  return data.includes('px') ? data : `${+data}px`
}
